<template>
  <el-dialog
    title="调整关联院校"
    :visible.sync="dialogVisible"
    :before-close="handleClose">
    
    <span style="margin-left:10px">院校名称：</span>
    <el-select
      size="small"
      v-model="schoolName"
      clearable
      filterable
      remote
      reserve-keyword
      @keyup.enter.native="handleFilter"
      placeholder="请输入关键词"
      :remote-method="getSchoolOptions"
      :loading="isSchoolLoading">
      <el-option v-for="item in schoolsByTitleOptions" :key="item.academyId" :label="item.academyName" :value="item.academyName">
      </el-option>
    </el-select>
    <span style="margin-left:30px">所属地区：</span>
    <el-select v-model="areaOption" placeholder="请选择" @keyup.enter.native="handleFilter">
      <el-option
        v-for="item in areas"
        :key="item.value"
        :label="item.label"
        :value="item.label">
      </el-option>
    </el-select>
    <el-button class="filter-item" style="margin: 0 0 30px 30px;" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
    <!-- <el-col style="margin: 10px 10px 30px;">
      <el-checkbox v-model="pushAllResult" @change="choAllSchool">选择全部院校</el-checkbox>
    </el-col> -->


    <el-table
      v-if="!pushAllResult"
      :data="schoolLists"
      v-loading="schoolListLoading"
      element-loading-text="数据加载中，请稍后"
      ref="list"
      @select='getEveryPageSlectionChanged'
      @select-all='getEveryPageSlectionAllChanged'
    >
      <el-table-column type="selection" width="100" align="center"></el-table-column>
      <el-table-column property="academyId" label="院校ID" width="100" align="center"></el-table-column>
      <el-table-column property="academyName" label="院校名称"></el-table-column>
    </el-table>

    <div v-show="!pushAllResult" class="pagination-container">
      <el-pagination 
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="schoolParams.pageNo"
        :page-sizes="[10,20,30,50]" 
        :page-size="schoolParams.pageSize" 
        layout="total, sizes, prev, pager, next, jumper" 
        :total="total"
      >
      </el-pagination>
    </div>

    <el-col style="margin: 20px 30px 30px 10px; width: 98%;">
      <b style="margin-left:10px">已选择院校列表：</b>
      <span>{{ getSchoolLists(momentSelectedArr) }}</span>
    </el-col>
    
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleSaveChoose">保 存</el-button>
    </span>

  </el-dialog>  
</template>

<script>
import { getAreaList } from '@/api/school'
import { nameAndProvince, queryLikeSchoolByName, addNewAcademy, querySchoolByProvince } from '@/api/marketer'
export default {
  name: 'SchoolSet',
  data() {
    return {
      dialogVisible: false,
      areas: [], // 地区多级联动结构化数组
      areaOption: '', // 地区多级联动v-model绑定
      schoolName: '', // 查询院校名称
      isSchoolLoading: false,
      pushAllResult: false, // false: 非全选 ; true : 全选
      marketerId: '', // 市场人员ID
      schoolListLoading: false,
      schoolParams: {
        marketerId: '',
        academyName: '',
        province: '',
        pageNo: 1,
        pageSize: 10
      },
      total: null,
      schoolLists: null,
      momentSelectedArr: [],
      schoolsByTitleOptions: [],
      addSchoolLists: []
    }
  },
  props: {
    dialog: {
      type: Boolean,
      default: false
    },

    setMsgObj: {
      type: Object,
      default: {},
      children: {
        setSchoolLists: {
          type: Array,
          default: []
        },
        setId: {
          type: Number,
          default: null
        }
      }
    }
  },
  watch: {
    dialog(boolean) {
      this.dialogVisible = boolean
      this.schoolName = ''
      this.areaOption = ''
      this.pushAllResult = ''
      this.schoolParams.province = ''
      this.schoolParams.academyName = ''
      this.getSchools()
    },
    setId(string) {
      this.marketerId = string
    },
    setMsgObj(obj) {
      this.momentSelectedArr = []
      for (const item of obj.setSchoolLists) {
        if (this.momentSelectedArr.indexOf(item) == -1) {
          this.momentSelectedArr.push(item)
        }
      }
      this.schoolParams.marketerId = obj.setId
    }

  },
  mounted() {
    this.fetchAreaData()
  },
  methods: {
    choAllSchool(val) {
      if (this.pushAllResult) {
        const params = {
          province: this.areaOption,
          academyName: this.schoolName,
          marketerId: this.schoolParams.marketerId
        }
        querySchoolByProvince(params).then(response => {
          if (response.code == 0) {
            this.addSchoolLists = response.data
            for (const item of response.data) {
              if (this.momentSelectedArr.indexOf(item) == -1) {
                this.momentSelectedArr.push(item)
              }
            }
          }
        })
      } else {
        for (const item of this.addSchoolLists) {
          if (this.momentSelectedArr.indexOf(item) !== -1) {
            this.momentSelectedArr = this.momentSelectedArr.filter(x => x !== item)
          }
        }
        this.addSchoolLists = []
      }
    },
    // 关联学校列表展示
    getSchoolLists(data) {
      let schoolLists = ''
      for (let i = 0; i < data.length; i++) {
        schoolLists += data[i].academyName
        if (i < data.length - 1) {
          schoolLists += '，'
        }
      }
      return schoolLists
    },
    // 点击模态框中的'X'
    handleClose() {
      const that = this
      this.$confirm('数据未保存，确认关闭？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        that.$emit('cancel')
      }).catch(() => {})
    },
    // 点击'保存'按钮
    handleSaveChoose() {
      const params = {
        marketerId: this.schoolParams.marketerId,
        academyIds: this.addSchoolLists
      }
      addNewAcademy(params).then(response => {
        if (response.code == 0) {
          this.$message({
            message: '关联院校成功',
            type: 'success',
            center: true
          })
        } else {
          this.$message({
            message: '关联院校失败',
            type: 'error',
            center: true
          })
        }
        this.$emit('cancel')
      })
    },
    // 点击'搜索'按钮
    handleFilter() {
      this.schoolParams.province = this.areaOption
      this.schoolParams.academyName = this.schoolName
      this.schoolParams.pageNo = 1
      this.getSchools()
    },
    // 获取'地区'详情
    fetchAreaData() {
      getAreaList().then(response => {
        this.areas = response.data
      })
    },
    getSchoolOptions(title) {
      if (title) this.GetSchoolsByTitleOptions(title)
    },

    GetSchoolsByTitleOptions(title) {
      const params = {
        academyName: title
      }
      queryLikeSchoolByName(params).then(response => {
        this.schoolsByTitleOptions = response.data
      })
    },

    getSchools() {
      this.schoolListLoading = true
      const { schoolParams } = this
      nameAndProvince(schoolParams).then(response => {
        const { code, data:{ total, list } } = response
        if(code == 0){
          this.total = total
          this.schoolLists = list
          this.schoolListLoading = false
        }
      })
    },
    handleSizeChange(val) {
      this.schoolParams.pageSize = val
      this.getSchools()
    },
    handleCurrentChange(val) {
      this.schoolParams.pageNo = val
      this.getSchools()
    },

    // 单选触发的事件
    getEveryPageSlectionChanged(selection, row) {
      let isSeleted = false
      for (const item of this.momentSelectedArr) {
        if (item.academyId == row.academyId) {
          isSeleted = true
        }
      }
      if (!isSeleted) {
        this.momentSelectedArr.push(row)
        this.addSchoolLists.push(row)
      } else{
        this.momentSelectedArr = this.momentSelectedArr.filter(x => x.academyId != row.academyId)
        this.addSchoolLists = this.addSchoolLists.filter(x => x.academyId != row.academyId)
      }
    },
    // 全选触发的事件
    getEveryPageSlectionAllChanged(selection) {
      if (selection.length > 0) {
        for (const item of selection) {
          const index = this.momentSelectedArr.indexOf(item)
          if (index == -1) {
            this.momentSelectedArr.push(item)
            this.addSchoolLists.push(item)
          }
        }
      } else {
        for (const item of this.schoolLists) {
          this.momentSelectedArr = this.momentSelectedArr.filter(x => x.academyId != item.academyId)
          this.addSchoolLists = this.addSchoolLists.filter(x => x.academyId != item.academyId)
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .pagination-container{
    margin-top:30px;
  }
</style>
